/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.OnlineHouseLeaseSystem.common;

import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 *
 * @author gas1121
 */
public class SetCharacterEncodingFilter implements Filter {

    private FilterConfig filterConfig = null;
    private String encoding = null;
    private boolean ignore = true;

    /**
     *
     * @param request The servlet request we are processing
     * @param response The servlet response we are creating
     * @param chain The filter chain we are processing
     *
     * @exception IOException if an input/output error occurs
     * @exception ServletException if a servlet error occurs
     */
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain)
	throws IOException, ServletException {

        if(ignore || request.getCharacterEncoding() == null)
        {
            String encoding = selectEncoding(request);
            if(encoding != null)
                request.setCharacterEncoding(encoding);
        }
        chain.doFilter(request, response);
    }

    protected String selectEncoding(ServletRequest request) {
    return (this.encoding);
    }
    
    /**
     * Return the filter configuration object for this filter.
     */
    public FilterConfig getFilterConfig() {
	return (this.filterConfig);
    }

    /**
     * Set the filter configuration object for this filter.
     *
     * @param filterConfig The filter configuration object
     */
    public void setFilterConfig(FilterConfig filterConfig) {
	this.filterConfig = filterConfig;
    }

    /**
     * Destroy method for this filter 
     */
    public void destroy() {
        this.encoding = null;
        this.filterConfig = null;
    }

    /**
     * Init method for this filter 
     */
    public void init(FilterConfig filterConfig) throws ServletException {
	this.filterConfig = filterConfig;
        this.encoding = filterConfig.getInitParameter("encoding");
        String value = filterConfig.getInitParameter("ignore");
	if(value == null)
            this.ignore = true;
        else if(value.equalsIgnoreCase("true"))
            this.ignore = true;
        else if(value.equalsIgnoreCase("yes"))
            this.ignore = true;
        else
            this.ignore = false;
    }
}
